package ch.zbw.pra.sysventory.domain.scanner;

import ch.zbw.pra.sysventory.domain.model.Processor;
import ch.zbw.pra.sysventory.domain.util.MyLogger;
import ch.zbw.pra.sysventory.ui.DetailLabel;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.EnumVariant;
import com.jacob.com.Variant;

public class ScanProcessor {

	private static final org.slf4j.Logger log = org.slf4j.LoggerFactory
			.getLogger(ScanProcessor.class);

	// Init data Typs

	public String nameProcessor;
	public String familyProcessor;
	public int coresProcessor;
	public int clockProcessor;

	private Processor cpu;

	// Constructor
	public ScanProcessor() {
	}

	/*
	 * Read entrys from Processor
	 */
	public Processor getProcessor() {
		String host = "localhost";
		String connectStr = String.format("winmgmts:\\\\%s\\root\\CIMV2", host);
		String query = "SELECT * FROM Win32_Processor";

		try {
			ActiveXComponent axWMI = new ActiveXComponent(connectStr);
			// Execute the query
			Variant vCollection = axWMI.invoke("ExecQuery", new Variant(query));

			// The Result is a Collection
			EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());
			Dispatch item = null;
			while (enumVariant.hasMoreElements()) {
				item = enumVariant.nextElement().toDispatch();
				// Dispatch.call returns a Variant which we can convert to a
				// java
				// form.
				String nameProcessor = Dispatch.call(item, "Name").toString();
				String familyProcessor = Dispatch.call(item, "Family").toString();
				String cores = Dispatch.call(item, "NumberOfCores").toString();
				String clock = Dispatch.call(item, "MaxClockSpeed").toString();
				int coresProcessor = Integer.valueOf(cores).intValue();
				int clockProcessor = Integer.valueOf(clock).intValue();

				MyLogger.logDebug(log, nameProcessor + " Familie: " + familyProcessor + " Cores: "
						+ coresProcessor + " Speed in MHz: " + clockProcessor);
				DetailLabel.setTextDetailLabel(nameProcessor);
				cpu = new Processor(nameProcessor, familyProcessor, coresProcessor, clockProcessor);

			}
		} catch (Exception e) {
			MyLogger.logError(log, e.toString());
		}

		return cpu;

	}

}
